<template>
  <component :is="config.layout.layoutMode"></component>
</template>
<script lang="ts" setup>
import { onMounted, onBeforeMount, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useConfig } from "@/store/config";
import { useNavTabs } from "@/store/navTabs";
import { useAdminInfo } from "@/store/adminInfo";
import Default from "@/layouts/backend/container/default.vue"; //布局组件
import Classic from "@/layouts/backend/container/classic.vue"; //布局组件
import Dashboard from "./container/dashboard.vue";
import {
  setAuthNodeRuoyi,
  getMenuPaths,
  getFirstRoute,
  routePush,
  addRouteAll,
  handleForRouyi,
  beforeAddRouteAll,
} from "@/utils/router";
import { adminBaseRoute } from "@/router/static"; //引入router
import { Session } from "@/utils/storage";
import { BEFORE_RESIZE_LAYOUT } from "@/store/constant/cacheKey"; // 切换到手机端前的上次布局方式
import { useRegion } from "@/store/backend/SysM/region";
import { useBigBoardB } from "@/store/backend/BigBoard/bigBoard2";
import { debounce, getDictData } from "@/utils/common";
import { useAccess } from "@/store/backend/DeviceM/access";
import { useOverView } from "@/store/backend/EquipM/overView";
import { useWorkOrder } from "@/store/backend/WorkOrder/order";
import { useLineCruiseTask } from "@/store/backend/LineCruiseM/task";
import { useDictionary } from "@/store/backend/tool/dictionary";

const route = useRoute();
const router = useRouter();
const config = useConfig();
const navTabs = useNavTabs();
const adminInfo = useAdminInfo();
const region = useRegion();
const bigBoardB = useBigBoardB();
const access = useAccess();
const overView = useOverView();
const workOrder = useWorkOrder();
const line = useLineCruiseTask();
const dictionary = useDictionary();

onMounted(() => {
  init();
  onSetNavTabsMinWidth();
  window.addEventListener("resize", onSetNavTabsMinWidth);
});

onBeforeMount(() => {
  onAdaptiveLayout();
  window.addEventListener("resize", debounce(onAdaptiveLayout, 1000));
  //获取个人信息
  adminInfo.getAdminInfo().then((res: any) => {
    adminInfo.dataFill(res.user);
    // if (res.roles.includes("admin")) unExamineWorkOrders();
    // res.roles[0] === "qy" || res.roles[0] === "user"
    //   ? (access.switch = true)
    //   : (access.switch = false);
    // res.user.userType === "2" ? (overView.main = true) : "";
    // access.companyid = res.user.companyid;
    // region.usrRegionIds = res.regions;
    //非admin用户必须折叠aside菜单
    res.user.userName === "admin" ? "" : config.changeMenuCollapse(true);
    setAuthNodeRuoyi("/admin/", res.permissions);
  });
});
onUnmounted(() => {
  window.removeEventListener("resize", onAdaptiveLayout);
  window.removeEventListener("resize", onSetNavTabsMinWidth);
});

//index()方法 获取adminInfo/menus/siteConfig信息
const init = () => {
  adminInfo.getRouters().then((res: any) => {
    handleForRouyi(res.data);
    // navTabs.setTabsViewRoutes(res.data);
    beforeAddRouteAll(res.data).then((result) => {
      const viewsComponent = import.meta.glob("/src/views/backend/**/*.vue");
      addRouteAll(viewsComponent, result, adminBaseRoute.name as string);
      if (res.data) {
        // 预跳转到上次路径
        // console.log("route.query", route.query);
        // console.log("adminBaseRoute.path", adminBaseRoute.path);
        if (
          route.query &&
          route.query.url &&
          route.query.url != adminBaseRoute.path
        ) {
          // 检查路径是否有权限
          let menuPaths = getMenuPaths(navTabs.state.tabsViewRoutes as any);
          if (menuPaths.indexOf(route.query.url as string) !== -1) {
            let query = JSON.parse(route.query.query as string);
            routePush({
              path: route.query.url as string,
              query: Object.keys(query).length ? query : {},
            });
            return;
          }
        }
        // 找到第一个菜单后跳转
        let firstRoute = getFirstRoute(navTabs.state.tabsViewRoutes as any);
        if (firstRoute) routePush(firstRoute.path);
      }
    });
  });
};
/**
 * 左侧边栏折叠之后在不同尺寸下是否隐藏
 * 顶部类似面包屑导航是否切换为经典模式
 */
const firstRegion = () => {
  region.getRegionByRole().then(() => {
    //获取所有设备这个方法一定要提前 保证第一次与第二次方法调用时间相近
    bigBoardB.getAllDevices(
      {
        pageSize: 10000,
        regions: region.regionIds + "",
      },
      true
    );
  });
};
//获取工序类型字典
if (
  JSON.stringify(dictionary.processType) == "{}" ||
  !JSON.stringify(dictionary.processType["type"])
) {
  dictionary.getDictInfo("sys_process_type").then((res: any) => {
    dictionary.processType["type"] = getDictData(res);
    console.log("工序类型", dictionary.processType);
  });
}
//获取未审核0或者未考核4工单
const unExamineWorkOrders = () => {
  workOrder
    .getSingleAndListOrderAuto({
      status: "0",
    })
    .then((res: any) => {
      console.log("待派工工单数据", res);
      workOrder.topNewsNum = res.total;
      workOrder.topNewsObj = res.rows;
      workOrder
        .getSingleAndListOrderAuto({
          status: "3",
        })
        .then((res: any) => {
          console.log("已完工工单数据", res);
          if (res.rows.length > 0) {
            workOrder.topNewsNum += res.total;
            workOrder.topNewsObj.push(...res.rows);
          }
        });
    });
};

// const alert = () => {
//   console.log("route.query.url", route.query, route.query.url);
// };
const onAdaptiveLayout = () => {
  // console.log("region.regionIds.length", region.regionIds.length);
  //获取权限查询区域树将id遍历出来
  // firstRegion();
  // region.regionIds.length ? alert() : firstRegion();
  let html = document.documentElement;
  const clientWidth = document.body.clientWidth; //获取屏幕实际宽度
  console.log("获取屏幕实际宽度", clientWidth);
  const clientHeight = document.body.clientHeight; //获取屏幕高度
  console.log("获取屏幕实际宽度", clientHeight, "获取屏幕高度", clientHeight);

  if (
    route.path === "/admin/BigBoard/bigBoard1" ||
    route.path === "/admin/BigBoard/bigBoard2" ||
    route.path === "/admin/Bigboard/bigboardFirst"
  ) {
    html.style.fontSize = clientWidth / 80 + "px";
    console.log("html.style.fontSize", html.style.fontSize);
    return;
  } //大屏页面不切换到经典与默认布局
  let defaultBeforeResizeLayout = {
    layoutMode: (config.layout.layoutMode = "Dashboard"), //后台布局
    menuCollapse: config.layout.menuCollapse, //是否水平折叠收起菜单
  };
  let beforeResizeLayout = Session.get(BEFORE_RESIZE_LAYOUT); // 切换到手机端前的上次布局方式
  console.log("beforeResizeLayout", beforeResizeLayout);
  if (!beforeResizeLayout)
    Session.set(BEFORE_RESIZE_LAYOUT, defaultBeforeResizeLayout);
  // const clientWidth = document.body.clientWidth; //获取屏幕实际宽度
  if (clientWidth < 1024) {
    console.log(
      "当屏幕宽度小于1024时clientWidth < 1024",
      route,
      route.path,
      route.query.url
    );
    if (
      route.path === "/admin/Bigboard/bigboardFirst" ||
      route.path === "/admin/BigBoard/bigBoard1"
    ) {
    } else {
      //非大屏页面
      config.setLayout("menuCollapse", true); //将菜单水平折叠起来
      config.setLayout("shrink", true); //收缩布局
      config.setLayoutMode("Classic"); //切换为经典模式 顶栏只剩下一个唤起侧边栏的按钮
      html.style.fontSize = clientWidth / 80 + "px";
      console.log("html.style.fontSize", html.style.fontSize);
    }
  } else {
    console.log(
      "当屏幕宽度大于1024时clientWidth > 1024",
      route,
      route.path,
      route.query,
      route.query.url
    );
    if (
      route.path === "/admin/Bigboard/bigboardFirst" ||
      route.path === "/admin/BigBoard/bigBoard1"
    ) {
      console.log("大屏页面");

      //切换为之前存储的布局模式
      let beforeResizeLayoutTemp = defaultBeforeResizeLayout;
      // console.log(
      //   "这边",
      //   beforeResizeLayoutTemp,
      //   beforeResizeLayout,
      //   defaultBeforeResizeLayout
      // );
      config.setLayout("menuCollapse", beforeResizeLayoutTemp.menuCollapse);
      config.setLayout("shrink", false);
      config.setLayoutMode(beforeResizeLayoutTemp.layoutMode);
      html.style.fontSize = clientWidth / 80 + "px";
    } else {
      console.log("非大屏页面");

      //非大屏页面
      let defaultBeforeResizeLayout = {
        layoutMode: (config.layout.layoutMode = "Default"), //后台布局
        menuCollapse: config.layout.menuCollapse, //是否水平折叠收起菜单
      };
      let beforeResizeLayoutTemp = defaultBeforeResizeLayout;
      // console.log(
      //   "那边",
      //   beforeResizeLayoutTemp,
      //   beforeResizeLayout,
      //   defaultBeforeResizeLayout
      // );
      config.setLayout("menuCollapse", beforeResizeLayoutTemp.menuCollapse);
      config.setLayout("shrink", false);
      config.setLayoutMode(beforeResizeLayoutTemp.layoutMode);
      html.style.fontSize = clientWidth / 80 + "px";
    }
  }
};

// 在实例挂载后为navTabs设置一个min-width，防止宽度改变时闪现滚动条
const onSetNavTabsMinWidth = () => {
  const navTabs = document.querySelector(".nav-tabs") as HTMLElement;
  if (!navTabs) {
    return;
  }
  const navBar = document.querySelector(".nav-bar") as HTMLElement;
  const navMenus = document.querySelector(".nav-menus") as HTMLElement;
  const minWidth = navBar.offsetWidth - (navMenus.offsetWidth + 20);
  navTabs.style.width = minWidth.toString() + "px";
};
</script>
<!-- 异步加载 只有在 components 选项中的组件可以被动态组件使用-->
<script lang="ts">
export default {
  components: { Default, Classic, Dashboard },
};
</script>
<style lang="scss" scoped></style>
